package com.jx.driving.protocol.terminal.codec;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;

import org.apache.commons.lang3.StringUtils;

/**
 * 定长string读写器,超过长度会被截取. 小于指定长度,后面补0
 * 
 * @author shenliuyang
 *
 *         2016年8月1日上午10:39:11
 */
public class LimitedStringReaderWriter extends FieldReaderWriter {

	public LimitedStringReaderWriter(Field field, int size, int order) {
		super(field, size, order);
	}

	@Override
	public void read(InputStream in, Object to) throws IOException {
		StringBuilder sb = new StringBuilder(size);
		for (int i = 0; i < size; i++) {
			sb.append((char) in.read());
		}
		wrtietoField(to, sb.toString());
	}

	@Override
	public void write(OutputStream out, Object from) throws IOException {
		byte[] data = new byte[size];
		String value = (String) readFromField(from);
		value = value == null ? "" : value;
		if (StringUtils.isNotBlank(value)) {
			for (int i = 0; i < size; i++) {
				data[i] = (byte) (value.length() > i ? value.charAt(i) : '0');
			}
		}
		out.write(data);
	}

}
